// package-market/pages/lottery-draw/index.js
const app = getApp();
import { UserInfoUpdateMixins, ShareImageMixins } from '../../../behaviors/page';
import { tipToast, showLoading, hideLoading } from '../../../common/env';
import { ACTIVITY_STATUS_VALUE } from '../../../constants/activity';
import { LOTTERY_ACTIVITY_TYPE } from '../../constants/lottery';
import { getLotteryActivityDetail, getAwardReporterList, doInvokeLottery } from '../../api/lottery';
let loaded = false, activityId;

Page({
    mixins: [UserInfoUpdateMixins, ShareImageMixins],
    data: {
        LOTTERY_ACTIVITY_TYPE,
        noticeList: [],
        activityInfo: {},
        lotteryInfo: {},
        procedureInfo: {},
        lotteryResult: {},
    },
    onLoad(options) {
        activityId = options.activityId;
        app.event.addListener('sendLotteryActivityInfoForDraw', this._handleGetActivity.bind(this));
    },
    onShow() {
        this._handleGetDetail();
    },
    onUnload() {
        app.event.removeListener('sendLotteryActivityInfoForDraw');
    },
    _handleGetActivity(activityInfo) {
        this.setData({
            activityInfo,
        });
    },
    async _handleGetDetail() {
        !loaded && showLoading('加载中...');
        const { lotteryInfo, procedureInfo } = await getLotteryActivityDetail(activityId);
        const noticeList = await getAwardReporterList(activityId);
        console.log('LotteryDraw => 抽奖活动详情为', { lotteryInfo, procedureInfo });
        this.setData({
            noticeList,
            lotteryInfo,
            procedureInfo,
        });
        if (!loaded) hideLoading(); loaded = true;
    },
    async handleDoAward(e) {
        const { lotteryInfo, procedureInfo } = this.data;
        if (lotteryInfo.processStatus !== ACTIVITY_STATUS_VALUE.processing) {
            tipToast('抽奖活动结束了');
            return;
        }
        if (procedureInfo.availableCount <= 0) {
            tipToast('抽奖机会用完了');
            return;
        }
        let lotteryResult = { ...e.detail };
        const flag = await doInvokeLottery({ activityId });
        if (flag) {
            const { awardInfos, procedure } = flag;
            lotteryResult.prize = awardInfos && awardInfos.length ? awardInfos[0].prize : -1;
            this.setData({
                lotteryResult,
                procedureInfo: procedure,
            });
        }
    },
})
